package com.example.app.service;

import com.example.app.dao.LiveLocationDto;
import com.example.app.entity.LiveLocation;
import com.example.app.mapper.LiveLocationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class LiveLocationService {
    private final LiveLocationMapper liveLocationRepository;
    private final FriendService friendService;
    private final SimpMessagingTemplate messagingTemplate; // WebSocket 推送

    @Transactional
    public void updateLocation(Long userId, double lat, double lon) {
        LiveLocation location = liveLocationRepository.findLiveLocationById(userId);
        if (location == null) {
            location = new LiveLocation(userId, lat, lon);
        }
        location.setLatitude(lat);
        location.setLongitude(lon);
        location.setUpdatedAt(LocalDateTime.now());
        location.setSharing(true);
        liveLocationRepository.insertLiveLocation(location);

        // 通知好友位置更新（WebSocket 推送）
        List<Long> friendIds = friendService.getFriendIds(userId);
        for (Long fid : friendIds) {
            messagingTemplate.convertAndSend("/topic/location/" + fid,
                    Map.of("userId", userId, "lat", lat, "lon", lon, "time", location.getUpdatedAt()));
        }
    }

    public void stopSharing(Long userId) {
        LiveLocation liveLocation = liveLocationRepository.findLiveLocationById(userId);
        if (liveLocation != null) {
            liveLocation.setSharing(false);
        }
        liveLocationRepository.updateLiveLocation(liveLocation);
    }

    public List<LiveLocationDto> getFriendsLiveLocations(Long userId) {
        List<Long> friendIds = friendService.getFriendIds(userId);
        return liveLocationRepository.findAllByUserIdInAndSharingTrue(friendIds)
                .stream()
                .map(LiveLocationDto::fromEntity)
                .toList();
    }
}
